/**
 * Adapter danh sach cac bai hat Online
 */
package com.toidep.adapters;

import java.util.ArrayList;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.toidep.R;
import com.toidep.activities.MainActivity;
import com.toidep.api.ApiController;
import com.toidep.api.ParseJSON;
import com.toidep.base.BaseFragment;
import com.toidep.bitmaputil.ImageWorker;
import com.toidep.config.ConfigUtility;
import com.toidep.config.Constants;
import com.toidep.entities.VideoEntity;
import com.toidep.interfaces.ResponseListener;
import com.toidep.widgets.sectionlist.AmazingAdapter;

public class VideoSuggestionAdapter extends AmazingAdapter{

	private MainActivity mainActivity;
	private BaseFragment parentFragment;
	
	private ArrayList<VideoEntity> listVideo;
	public ArrayList<ViewHolder> arrViewHolder;				// QUan ly cac ViewHolder

	private int widthImage, heightImage;
	private int widthImageView, heightImageView;
	
	private int adapterTypeByScreen = -1;					// Adapter nay cua Screen nao de goi API tuong ung cho dung
	private String currentVideoId = null;
	
	/**
	 * Constructor
	 * Khoi tao Adapter lay danh sach videos theo mode 
	 * @param ff
	 * @param adapterType Adapter Screen Type
	 * @param type = All, Top, New, Hot
	 */
	public VideoSuggestionAdapter(BaseFragment ff, int adapterType, String currentVideoId) {
		this.mainActivity = (MainActivity) ff.getActivity();
		this.parentFragment = ff;
		this.listVideo = new ArrayList<VideoEntity>();
		this.arrViewHolder = new ArrayList<ViewHolder>();

		this.adapterTypeByScreen = adapterType;
		this.currentVideoId = currentVideoId;
	}
	
	public void setParentId(String parent_id) {
		this.currentVideoId = parent_id;
	}
	
	public void setAvatarImageSize() {
		widthImage = ConfigUtility.size_half_width;
		heightImage = (int) (widthImage*ConfigUtility.scale_size_horizontal_thumbs_item);

		widthImageView = (int) (ConfigUtility.scrWidth*ConfigUtility.scale_thumbs_news_width);
		heightImageView = (int) (widthImageView*ConfigUtility.scale_size_horizontal_thumbs_item);
	}
	
	public ArrayList<VideoEntity> getListVideo() {
		return this.listVideo;
	}
	
	public void resetList(ArrayList<VideoEntity> l) {
		if (listVideo == null) {
			listVideo = new ArrayList<VideoEntity>();
		}
		//===== Tao Mang ViewHolder=====
		if (arrViewHolder == null) {
			arrViewHolder = new ArrayList<ViewHolder>();
		}
		arrViewHolder.clear();
		for (int i = 0; i < l.size(); i++) {
			arrViewHolder.add(null);
		}
		//==============================
		listVideo.clear();
		listVideo.addAll(l);
		notifyDataSetChanged();
	}
	
	public void resetList() {
		if (listVideo == null) {
			listVideo = new ArrayList<VideoEntity>();
		}
		if (arrViewHolder == null) {
			arrViewHolder = new ArrayList<ViewHolder>();
		}
		listVideo.clear();
		
		getFirstPage();
	}
	
	public int getCount() {
		if (listVideo != null)
			return listVideo.size();
		else 
			return 0;
	}

	public VideoEntity getItem(int position) {
		return listVideo.get(position);
	}

	public long getItemId(int position) {
		return position;
	}
	
	// TODO: onNextPageRequested
	@Override
	protected void onNextPageRequested(int page) {
		getVideosSuggestion(page);
	}

	@Override
	protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
		// do nothing
	}
	
	private class ViewHolder {
		public ImageView image;
		public FrameLayout layoutContain;
	}

	@Override
	public View getAmazingView(int position, View convertView, ViewGroup parent) {
		final ViewHolder viewHolder;
		if (convertView == null) {
			
			convertView = parentFragment.getActivity().getLayoutInflater().inflate(R.layout.layout_itemlist_video_suggestion, null);
			viewHolder = new ViewHolder();
			viewHolder.layoutContain = (FrameLayout) convertView.findViewById(R.id.contain);
			viewHolder.image = (ImageView) viewHolder.layoutContain.findViewById(R.id.imgSuggest);
			
			FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(widthImageView, heightImageView);
			viewHolder.image.setLayoutParams(layoutParams);
//			viewHolder.image.setScaleType(ScaleType.FIT_CENTER);
//			viewHolder.layoutContain.addView(viewHolder.image);
			
			convertView.setTag(viewHolder);
			
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
			
			FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(widthImageView, heightImageView);
			viewHolder.image.setLayoutParams(layoutParams);
//			viewHolder.image.setScaleType(ScaleType.FIT_CENTER);
		}
		
		final VideoEntity currentItem = getItem(position);
		
		// Load avatar
		viewHolder.image.setTag(currentItem.getThumb());
		mainActivity.loadImage(viewHolder.image, currentItem.getThumb(),
				widthImage, heightImage, widthImageView, heightImageView);
		
		// Them vao mang ViewHolder
		try {
			arrViewHolder.set(position, viewHolder);
		} catch (Exception e) {
		}
		
		// Load description
		TextView textVideoTitle = (TextView) convertView.findViewById(R.id.textviewVideoTitle);
		textVideoTitle.setText(currentItem.getTitle());
		TextView textCreated = (TextView) convertView.findViewById(R.id.textVideoCreated);
		textCreated.setText(currentItem.getCreated());
		TextView textViewCount = (TextView) convertView.findViewById(R.id.textViewCount);
		textViewCount.setText(currentItem.getTotalView());
		TextView textDuration = (TextView) convertView.findViewById(R.id.txtDuration);
		textDuration.setVisibility(View.VISIBLE);
		textDuration.setText(currentItem.getDuration());
		
		return convertView;
	}

	@Override
	public void configurePinnedHeader(View header, int position, int alpha) {
		
	}

	@Override
	public int getPositionForSection(int section) {
		return 0;
	}

	@Override
	public int getSectionForPosition(int position) {
		return 0;
	}

	@Override
	public int getSectionPosition(int position) {
		return 0;
	}

	@Override
	public Object[] getSections() {
		return null;
	}
	
	/**
	 * Clear Adapter ve null
	 */
	public void clear() {
		resetPage();
		listVideo.clear();
//		listSong = null;
		clearTemporarity();
		notifyDataSetChanged();
	}
	
	/**
	 * Xoa cac bien su dung: ViewHolder...
	 */
	public void clearTemporarity() {
		if (arrViewHolder != null)
			arrViewHolder.clear();
//		arrViewHolder = null;
	}
	
	/**
	 * Cancel cac task load anh khi close fragment
	 */
	public void pauseLoadingImage() {
		if (arrViewHolder != null) {
			for (ViewHolder viewHolder : arrViewHolder) {
				try {
					if (viewHolder.image != null) {
						ImageWorker.cancelWork(viewHolder.image);
					}
				} catch (Exception e) {
				}
			}
		}
	}
	
	/**
	 * Clear memory cache
	 */
	public void clearMemoryCacheOnly() {
		Log.e("SongsAdapter", "clearMemoryCacheOnly");
//		imageFetcher.clearMemoryCacheOnly();
	}
	
	/**
	 * Goi ham nay khi Fragment chua no xay ra onDestroy
	 */
	public void destroyAdapter() {
		clear();
		listVideo = null;
		arrViewHolder = null;
//		imageFetcher = null;
	}
	
	// ======================== GOI API TUONG UNG VOI CAC ADAPTER ==========================
	
	/**
	 * List Videos NORMAL trong VideoFragment
	 * Lay danh sach Videos theo categories NEW - HOT - TOP - ALL
	 */
	private void requestAPI(int page, ResponseListener responseListener) {
		ApiController.getRelation(parentFragment.getActivity(), Constants.RELATION_TYPE_VIDEO, "" + currentVideoId, 
				page, ConfigUtility.PAGE_SIZE, responseListener);
	}
	
	private void getVideosSuggestion(int page) {

		ResponseListener responseListener = new ResponseListener() {
			
			@Override
			public void processResponse(int inintstall) {
				notifyNoMorePages();
			}
			
			@Override
			public void processResponse(String response) {
				if (response != null) {
					try {
						ArrayList<VideoEntity> list = ParseJSON.getAllVideoObjectFromResponse(response);
						if (list != null && list.isEmpty() == false) {
							listVideo.addAll(list);
							//===== Tao Mang ViewHolder=====
							for (int i = 0; i < list.size(); i++) {
								arrViewHolder.add(null);
							}
							//==============================
							nextPage();
							notifyDataSetChanged();
							if (list.size() < ConfigUtility.PAGE_SIZE)
								notifyNoMorePages();
							else
								notifyMayHaveMorePages();
						} else {
							notifyNoMorePages();
						}
					} catch (Exception e) {
						notifyNoMorePages();
					} finally {
						isLoadingMore = false;
					}
				} else {
					notifyNoMorePages();
				}
				
			}
		};

		requestAPI(page, responseListener);
	}
	
	private void getFirstPage() {
		int page = 1;
		ResponseListener responseListener = new ResponseListener() {
			
			@Override
			public void processResponse(int inintstall) {
				notifyNoMorePages();
			}
			
			@Override
			public void processResponse(String response) {
				if (response != null) {
					ArrayList<VideoEntity> list = ParseJSON.getAllVideoObjectFromResponse(response);
					if (list != null && list.isEmpty() == false) {
						notifyMayHaveMorePages();
						
						resetList(list);
					} else {
						notifyNoMorePages();
					}
				} else {
					notifyNoMorePages();
				}
			}
		};

		requestAPI(page, responseListener);
	}

	public void onItemClick(int position) {
		if (getCount() == 0) return;
		mainActivity.openDetailVideo(getItem(position));
	}
}
